import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { type WebInfo } from '../types/webInfo'
export const useWebInfoStore = defineStore('webInfo', () => {
  let webInfo = reactive<WebInfo>({
    banner: [],
    cate: [],
    company_end: '',
    company_logo: '',
    site_name: '',
    hot_goods: [],
    company_electron_license_url: ''
  })
  let cateTree = JSON.parse(localStorage.getItem('cateTree')!) || reactive([])
  // 设置网站信息
  const setWebInfo = async (info: any) => {
    console.log('webinfo', info)
    const temp = await handleCate(info.cate)
    info.cate = info.cate.slice(0, 6)
    info.cate.push({
      id: 951231,
      cate_title: '关于我们'
    })
    const objectsFromMap = Array.from(temp).map(([key, value]: any) => ({ key, value }))
    cateTree.push(...objectsFromMap)
    localStorage.setItem('cateTree', JSON.stringify(cateTree))
    webInfo = Object.assign(webInfo, info)
  }

  function handleCate(cate: any): any {
    return new Promise((resolve, reject) => {
      let arr = new Map()
      cate.forEach((item: any, index: number) => {
        // arr.set(item.catalog_id, item)
        arr.set(item.id, item)
        if (index == cate.length - 1) {
          resolve(arr)
        }
      })
    })
  }

  return {
    webInfo,
    cateTree,
    setWebInfo
  }
})
